/*
 * :file description: 
 * :name: \redux_project\src\redux\todos\todosSlice.ts
 * :author: linkeda
 * :copyright: (c) 2025, Tungee
 * :date created: 2025-08-28 11:31:08
 * :last editor: linkeda
 * :date last edited: 2025-08-28 11:37:06
 */
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type { Todo, TodosState } from './types';

// 初始状态
const initialState: TodosState = {
  todos: [],
};

// 创建Todo Slice
const todosSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    // 添加Todo
    addTodo: (state, action: PayloadAction<{ text: string }>) => {
      const newTodo: Todo = {
        id: Date.now().toString(),
        text: action.payload.text,
        completed: false,
      };
      state.todos.push(newTodo);
    },
    
    // 删除Todo
    deleteTodo: (state, action: PayloadAction<{ id: string }>) => {
      state.todos = state.todos.filter(todo => todo.id !== action.payload.id);
    },
    
    // 切换Todo完成状态
    toggleTodo: (state, action: PayloadAction<{ id: string }>) => {
      const todo = state.todos.find(todo => todo.id === action.payload.id);
      if (todo) {
        todo.completed = !todo.completed;
      }
    },
    
    // 更新Todo文本
    updateTodo: (state, action: PayloadAction<{ id: string; text: string }>) => {
      const todo = state.todos.find(todo => todo.id === action.payload.id);
      if (todo) {
        todo.text = action.payload.text;
      }
    },
  },
});

// 导出actions
export const { addTodo, deleteTodo, toggleTodo, updateTodo } = todosSlice.actions;

// 导出reducer
export default todosSlice.reducer;